package linwen.wang.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import linwen.wang.order.mapper.OrderMapper;
import linwen.wang.order.entity.Order;
import linwen.wang.order.service.OrderService;
import linwen.wang.order.vo.User;
import lombok.extern.slf4j.Slf4j;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public Order findOrderById(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        /**
         * 使用httpclient
         * */
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        String url = "http://localhost:90/user/"+order.getUserId();
//        HttpGet httpGet = new HttpGet(url);
//        try {
//            CloseableHttpResponse response = httpClient.execute(httpGet);
//            HttpEntity responseEntity = response.getEntity();
//            String string = EntityUtils.toString(responseEntity);
//            User user = JSON.parseObject(string, User.class);
//            log.info("current user {}",string);
//            order.setUser(user);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        /**
         * 使用resttemplate
         * */

        String url = "http://localhost:90/user/"+order.getUserId();
        User user = restTemplate.getForObject(url, User.class);
        order.setUser(user);
        /**
         * 注册中心方式
         * */
//        List<ServiceInstance> instances = discoveryClient.getInstances("shop-user");
//        ServiceInstance serviceInstance = instances.get(0);
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();
//        URI uri = serviceInstance.getUri();
//        String url = "http://"+host+":"+port+"/user/"+order.getUserId();

        /**
         * 负载均衡下使用resttemplate
         * */
//        String url = "http://shop-user/user/"+order.getUserId();
//        User user = restTemplate.getForObject(url, User.class);
        /**
         * openFeign
         * */
//        User user = userMapper.getUserById(order.getUserId());
        // order.setUser(user);
        return order;
    }
}
